#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
激进精简案例5-8代码中的display语句，减少50%
"""

import re
import os

def reduce_display_aggressive(file_path):
    """
    激进精简策略：
    1. 只保留关键标题（包含====的display）
    2. 只保留步骤标题（第X步）
    3. 只保留完成标记
    4. 删除所有详细说明、列表、统计等
    """
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    new_lines = []
    removed_count = 0
    total_display = 0
    skip_until_next_section = False
    
    for i, line in enumerate(lines):
        # 统计display语句
        if line.strip().startswith('display'):
            total_display += 1
        
        # 保留非display行
        if not line.strip().startswith('display'):
            new_lines.append(line)
            continue
        
        # 保留主标题（包含====）
        if '====' in line:
            new_lines.append(line)
            skip_until_next_section = False
            continue
        
        # 保留步骤标题（第X步）
        if re.search(r'第.+步[:：]', line):
            new_lines.append(line)
            skip_until_next_section = False
            continue
        
        # 保留分隔线（----）但只在步骤标题后
        if '----' in line and not skip_until_next_section:
            new_lines.append(line)
            continue
        
        # 保留完成标记
        if any(marker in line for marker in ['完成', '成功', '✓', '✅', '已清理']):
            new_lines.append(line)
            continue
        
        # 保留日志文件路径
        if '.log' in line or '日志文件:' in line or '图表目录:' in line:
            new_lines.append(line)
            continue
        
        # 保留空行（但合并连续空行）
        if line.strip() == 'display ""':
            if new_lines and new_lines[-1].strip() != 'display ""':
                new_lines.append(line)
            else:
                removed_count += 1
            continue
        
        # 删除所有其他display语句
        removed_count += 1
    
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(new_lines)
    
    return total_display, removed_count

def main():
    """处理案例5-8的do文件"""
    
    files = [
        'do/cases_by_chapter/part3_advanced/case05_pricing_strategy.do',
        'do/cases_by_chapter/part3_advanced/case06_supply_chain_optimization.do',
        'do/cases_by_chapter/part3_advanced/case07_performance_prediction.do',
        'do/cases_by_chapter/part4_comprehensive/case08_customer_lifetime_value.do'
    ]
    
    print("=" * 70)
    print("激进精简案例5-8的display语句（目标：减少50%）")
    print("=" * 70)
    print()
    
    total_all = 0
    removed_all = 0
    
    for file_path in files:
        if not os.path.exists(file_path):
            print(f"⚠️  文件不存在: {file_path}")
            continue
        
        case_num = os.path.basename(file_path).split('_')[0].replace('case', '')
        print(f"处理案例{case_num}...")
        
        total, removed = reduce_display_aggressive(file_path)
        remaining = total - removed
        reduction_pct = (removed / total * 100) if total > 0 else 0
        
        print(f"  原始display语句: {total}个")
        print(f"  删除display语句: {removed}个")
        print(f"  保留display语句: {remaining}个")
        print(f"  精简比例: {reduction_pct:.1f}%")
        print()
        
        total_all += total
        removed_all += removed
    
    remaining_all = total_all - removed_all
    reduction_pct_all = (removed_all / total_all * 100) if total_all > 0 else 0
    
    print("=" * 70)
    print("总计")
    print("=" * 70)
    print(f"原始display语句总数: {total_all}个")
    print(f"删除display语句总数: {removed_all}个")
    print(f"保留display语句总数: {remaining_all}个")
    print(f"总体精简比例: {reduction_pct_all:.1f}%")
    print()
    
    if reduction_pct_all >= 50:
        print("✅ 精简完成！达到50%目标")
    else:
        print(f"⚠️  精简完成，但未达到50%目标（当前{reduction_pct_all:.1f}%）")
    print("=" * 70)

if __name__ == '__main__':
    main()

